package org.framework.rm.user;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.quickbundle.base.beans.factory.RmBeanFactory;
import org.quickbundle.base.web.page.RmPageVo;
import org.quickbundle.config.RmConfig;
import org.quickbundle.orgauth.IOrgauthConstants;
import org.quickbundle.orgauth.custom.impl.RmCustomOrgService;
import org.quickbundle.orgauth.rmparty.service.IRmPartyService;
import org.quickbundle.orgauth.rmparty.util.IRmPartyConstants;
import org.quickbundle.orgauth.rmpartyrelation.service.impl.RmPartyRelationService;
import org.quickbundle.orgauth.rmpartyrelation.vo.RmPartyRelationVo;
import org.quickbundle.orgauth.rmrole.service.IRmRoleService;
import org.quickbundle.orgauth.rmuser.service.IRmUserService;
import org.quickbundle.orgauth.rmuser.vo.RmUserVo;
import org.quickbundle.orgauth.util.impl.RmOrgService;
import org.quickbundle.project.IGlobalConstants;
import org.quickbundle.project.RmProjectHelper;
import org.quickbundle.project.cache.RmSqlCountCache;
import org.quickbundle.project.common.vo.RmCommonVo;
import org.quickbundle.tools.helper.RmJspHelper;
import org.quickbundle.tools.helper.RmPopulateHelper;
import org.quickbundle.tools.helper.RmSqlHelper;
import org.quickbundle.tools.helper.RmStringHelper;
import org.quickbundle.tools.helper.RmVoHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dfhc.ISystemConstant;
import com.dfhc.pub.concurrencycontrol.RequestConcurrentRoute;
import com.dfhc.pub.service.PubParamService;
import com.dfhc.rm.user.IUserConstants;
import com.dfhc.rm.user.service.UserService;
import com.dfhc.rm.user.vo.UserVo;
import com.dfhc.util.JspHelper;
import com.dfhc.util.StringHelper;

/**
 * @author ASUS
 * 会员列表(例子)
 */
@Controller
@RequestMapping(value = "/newRmUser")
public class newRmUserController implements IUserConstants {
	@Autowired
	private UserService userService;
	@Autowired
	private IRmUserService iRmUserService;
	@Autowired
	private PubParamService pubParamService;
	@Autowired
	private IRmRoleService roleService;
	@Autowired
	private RmPartyRelationService rmPartyRelationService;
	@Autowired
	private IRmRoleService iRmRoleService;
	/**
     * 简单查询，分页显示，支持表单回写
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "")
    public String list(Model model, HttpServletRequest request) {
    	model.addAttribute(ISystemConstant.QUERY_STRING, request.getQueryString());//全部参数
    	Map<String, Object> searchPara = getQueryByCondition(request);  //从request中获得查询条件
    	String queryCondition = getQueryCondition(request);  //从request中获得查询条件
        RmPageVo pageVo = RmJspHelper.transctPageVo(request, getCount(queryCondition));
        String orderStr = RmJspHelper.getOrderStr(request);  //得到排序信息
        List<RmUserVo> beans = iRmUserService.queryByCondition(queryCondition, orderStr, pageVo.getStartIndex(), pageVo.getPageSize());  //按条件查询全部,带排序
        RmJspHelper.saveOrderStr(orderStr, request);  //保存排序信息
        model.addAttribute(REQUEST_QUERY_CONDITION, searchPara);
        model.addAttribute(REQUEST_BEANS, beans);  //把结果集放入request
        return "/qb5activiti/newRmUser/listNewRmUser";
    }
    /**
     * 跳转到新增页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "/addPage")
    public String addPage(Model model, HttpServletRequest request) {    	            
        return "/qb5activiti/newRmUser/insertRmUser";
    }
    /**
     * 跳转到编辑和查看页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "/showPage")
    public String showPage(Model model, HttpServletRequest request) {
    	//获取id
    	String id = request.getParameter(IUserConstants.REQUEST_ID);
    	//根据id查询用户
    	if(!StringHelper.isEmpty(id)){
    		RmUserVo userVo = iRmUserService.find(id);
    		model.addAttribute(REQUEST_BEAN, userVo);
    	}
        return "/qb5activiti/newRmUser/insertRmUser";
    }
    
    /**
     * 跳转到编辑和查看页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "/detail")
    public String detail(Model model, HttpServletRequest request) {
    	//获取id
    	String id = request.getParameter(IUserConstants.REQUEST_ID);
    	//根据id查询用户
    	if(!StringHelper.isEmpty(id)){
    		RmUserVo userVo = iRmUserService.find(id);
    		model.addAttribute(REQUEST_BEAN, userVo);
    	}
    	RmUserVo bean = iRmUserService.find(request.getParameter(REQUEST_ID));  //通过id获取vo
    	confoneTo(bean);
        String queryCondition="CHILD_PARTY_ID='"+bean.getId()+"'";
		//查询用户所属的组织名称
        List<RmPartyRelationVo> vos = rmPartyRelationService.queryByCondition(queryCondition, null);
        if(vos!=null && vos.size()>0){
        	bean.setAttribute1(vos.get(0).getParent_party_name());
        }
        request.setAttribute(REQUEST_BEAN, bean);  //把vo放入request
        model.addAttribute(REQUEST_BEAN, bean);
        if(RM_YES.equals(request.getParameter(REQUEST_IS_READ_ONLY))) {
            request.setAttribute(REQUEST_IS_READ_ONLY, request.getParameter(REQUEST_IS_READ_ONLY));
        }
        return "/sample/member/detailRmUser";
    }

	private void confoneTo(RmUserVo bean) {
		String parent_party_name="";
    	StringBuilder orgFullPath = new StringBuilder();
		try {
				orgFullPath = new StringBuilder();
			if(bean.getParent_party_id() != null && bean.getParent_party_id().toString().length() > 0) {
				RmCommonVo thisParent = new RmCommonVo();
				thisParent.put("parent_party_code", bean.getParent_party_code().toString());
				List<RmCommonVo> lThisParent = new ArrayList<RmCommonVo>();
				lThisParent.add(thisParent);
				List<RmCommonVo> lParent = RmOrgService.getInstance().listAncestor(bean.getParent_party_id().toString(), IOrgauthConstants.PartyView.DEFAULT.id(), lThisParent);
				//lParent.remove(0);
				for(RmCommonVo vo1 : lParent) {
					if(orgFullPath.length() > 0) {
						bean.setCustom4(orgFullPath.toString());
						orgFullPath.append("->");
					}
					orgFullPath.append(vo1.getString("child_party_name"));
					bean.setCustom3(vo1.getString("child_party_name"));
				}
				
			}
		}catch(Exception e) {
			e.printStackTrace();
			orgFullPath.append(parent_party_name.toString());
		}
	}
	/**
     * 跳转到编辑和查看页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "/author")
    public String author(Model model, HttpServletRequest request) {
//    		Map<String, Object> dataMap = new HashMap<String, Object>();
    		String parent_party_id = "" ;
    		if(!"3".equals(RmProjectHelper.getRmUserVo(request).getAdmin_type())){
    			if(RmProjectHelper.getRmUserVo(request).getParty_id_org()!=null){
    				//公司id
    				parent_party_id = RmProjectHelper.getRmUserVo(request).getParty_id_org();
    			}
    		}
    		String party_id = request.getParameter("id"); //用户ID
    		RmUserVo rmUserVo = iRmUserService.find(party_id);
    		request.setAttribute("rmUserVo", rmUserVo);
    		String party_name="";
    		if(RmStringHelper.checkNotEmpty(party_id) && !"3".equals(RmProjectHelper.getRmUserVo(request).getAdmin_type())){
    			party_name = ((IRmPartyService)RmBeanFactory.getBean(IRmPartyConstants.SERVICE_KEY)).find(party_id).getName();
    		}
    		model.addAttribute("party_id",party_id);
    		model.addAttribute("party_name",party_name);
    		//查询该员工赋予的角色
    		List<RmCommonVo> roleListVo = RmProjectHelper.getCommonServiceInstance().doQuery("SELECT R.ID,PR.OWNER_ORG_ID,P.NAME from RM_ROLE R JOIN RM_PARTY_ROLE PR on R.ID=PR.ROLE_ID left join RM_PARTY P on P.OLD_PARTY_ID=PR.OWNER_ORG_ID  where R.USABLE_STATUS = '1' and PR.OWNER_PARTY_ID="+party_id);
    		Map<String, List<RmCommonVo>> mResult = new HashMap();
    		for(RmCommonVo vo:roleListVo){
    	  	  if(mResult.get(vo.getString("id")) == null) {
    	  		  mResult.put(vo.getString("id"), new ArrayList<RmCommonVo>());
    	  	  }
    	  	  mResult.get(vo.getString("id")).add(vo);
    		}
    		Map<String,String[]> mRole = new HashMap<String,String[]>();
    		for(String key:mResult.keySet()){
    			String companyName = "";
    			String companyId = "";
    	  	List<RmCommonVo> listv = mResult.get(key);
    	  	RmCommonVo sVo = listv.get(0);
    	  	String[] strs = new String[2];
    	  	for(RmCommonVo bVo:listv){
    	  		if(RmStringHelper.checkNotEmpty(bVo.getString("name")) && RmStringHelper.checkNotEmpty(bVo.getString("owner_org_id"))){
    	  			companyName += bVo.getString("name")+",";
    	  			companyId += bVo.getString("owner_org_id")+",";
    	  		}
    	  	}
    	  	if(RmStringHelper.checkNotEmpty(companyName)){
    	  		strs[0]=companyName.substring(0,companyName.length()-1);
    	  		strs[1]=companyId.substring(0,companyId.length()-1);
    	  	}
    	  	mRole.put(sVo.getString("id"),strs);
    	  }
    	  String[] roleIds = new String[mRole.size()];
    	  int j = 0;
    	  Map<String,Object> sWriteBack = new HashMap();
    	  for(Map.Entry<String,String[]> mr:mRole.entrySet()){
    	  	roleIds[j]=mr.getKey();
    			sWriteBack.put("company_id_"+mr.getKey(),mr.getValue().length>1 ? RmStringHelper.prt(mr.getValue()[1]):"");
    			sWriteBack.put("company_name_"+mr.getKey(),mr.getValue().length>1 ? RmStringHelper.prt(mr.getValue()[0]):"");
    			j++;
    	  }
    	  if(roleIds!=null&&roleIds.length>0){
  			sWriteBack.put("role_name", roleIds);
  			sWriteBack.put("role_name1", roleIds);
  		}
    		//根据权限查询角色
    		//RmCommonVo cVo = RmProjectHelper.getCommonServiceInstance().doQuery("select distinct(PR.CHILD_PARTY_CODE) from RM_PARTY_RELATION PR where PR.CHILD_PARTY_ID="+userVo.getCompany().getId()).get(0);
    		List<RmCommonVo> roleList = RmProjectHelper.getCommonServiceInstance().doQuery("SELECT ID,NAME,IS_SYSTEM_LEVEL, ROLE_CODE FROM RM_ROLE where USABLE_STATUS = '1'");
    		List<RmCommonVo> isSystemLevelList = new ArrayList<RmCommonVo>();
    		List<RmCommonVo> notSystemLevelList = new ArrayList<RmCommonVo>();
    		for(RmCommonVo vo:roleList){
    			if("1".equals(vo.getString("is_system_level"))){
    				isSystemLevelList.add(vo);
    			}else{
    				notSystemLevelList.add(vo);
    			}
    	  }
    		request.setAttribute("sWriteBack", sWriteBack);
//    		dataMap.put("isSystemLevelList", isSystemLevelList);
//    		request.setAttribute("list1", dataMap);
    		model.addAttribute("notSystemLevelList", notSystemLevelList);
    		model.addAttribute("isSystemLevelList", isSystemLevelList);
        return "/qb5activiti/newRmUser/auther-list";
    }
    /**
     * 从request中获得查询条件
     * @param request http请求对象
     * @return 条件Map
     */
    public static Map<String, Object> getQueryByCondition(HttpServletRequest request) {
        Map<String, Object> searchMap = null;
        if(request.getAttribute(REQUEST_QUERY_CONDITION) != null) {  //如果request.getAttribute中有，就不取request.getParameter
            searchMap = (Map<String, Object>)request.getAttribute(REQUEST_QUERY_CONDITION);
        } else {
           searchMap = new HashMap<String, Object>();
           searchMap.put("id", request.getParameter("id"));
           searchMap.put("name", request.getParameter("name"));
           searchMap.put("lockStatus", request.getParameter("lockStatus"));
           searchMap.put("loginId", request.getParameter("loginId"));
           searchMap.put("password", request.getParameter("password"));
           searchMap.put("authenType", request.getParameter("authenType"));
           searchMap.put("organizationId", request.getParameter("organizationId"));
           searchMap.put("employeeId", request.getParameter("employeeId"));
           searchMap.put("email", request.getParameter("email"));
           searchMap.put("adminType", request.getParameter("adminType"));
           searchMap.put("description", request.getParameter("description"));
           searchMap.put("agentStatus", request.getParameter("agentStatus"));
           searchMap.put("loginStatus", request.getParameter("loginStatus"));
           searchMap.put("lastLoginDate", request.getParameter("lastLoginDate"));
           searchMap.put("lastLoginIp", request.getParameter("lastLoginIp"));
           searchMap.put("loginSum", request.getParameter("loginSum"));
           searchMap.put("lastCustomCss", request.getParameter("lastCustomCss"));
           searchMap.put("isAffix", request.getParameter("isAffix"));
           searchMap.put("functionPermission", request.getParameter("functionPermission"));
           searchMap.put("dataPermission", request.getParameter("dataPermission"));
           searchMap.put("custom1", request.getParameter("custom1"));
           searchMap.put("custom2", request.getParameter("custom2"));
           searchMap.put("custom3", request.getParameter("custom3"));
           searchMap.put("custom4", request.getParameter("custom4"));
           searchMap.put("custom5", request.getParameter("custom5"));
           searchMap.put("customXml", request.getParameter("customXml"));
           searchMap.put("usableStatus", ISystemConstant.DICTIONARY_RM_YES_NOT_1);
           searchMap.put("modifyDate", request.getParameter("modifyDate"));
           searchMap.put("modifyIp", request.getParameter("modifyIp"));
           searchMap.put("modifyUserId", request.getParameter("modifyUserId"));
           searchMap.put("createTime", request.getParameter("createTime"));
           searchMap.put("createUserName", request.getParameter("createUserName"));
           searchMap.put("attribute1", request.getParameter("attribute1"));
           searchMap.put("attribute2", request.getParameter("attribute2"));
           searchMap.put("attribute3", request.getParameter("attribute3"));
           searchMap.put("attribute4", request.getParameter("attribute4"));
           searchMap.put("attribute5", request.getParameter("attribute5"));
           searchMap.put("delete_flag",ISystemConstant.DICTIONARY_RM_YES_NOT_0);
           searchMap.put("searchName", request.getParameter(ISystemConstant.SEARCH_NAME));
        }
        return searchMap;
    }
    /**
     * ajax 请求列表数据
     * @param model
     * @param request
     * @return
     * @throws IOException 
     */
    @RequestMapping(value = "/ajaxList",  produces="application/json")
    @ResponseBody
    public  Map<String,Object> ajaxList(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException{
          boolean bLock = false;
           Map<String,Object> dataMap=new HashMap<String,Object>();
           try{
	    	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
            //获取开始记录数
	    	String username =request.getParameter("userName");
	    	String queryCondition = getQueryCondition(request);  //从request中获得查询条件
	    	RmPageVo pageVo = RmJspHelper.transctPageVo(request, getCount(queryCondition));
	        String orderStr = RmJspHelper.getOrderStr(request);  //得到排序信息  //得到排序信息
	        int totalNum = iRmUserService.getRecordCount(queryCondition);
	        List<RmUserVo> beans = iRmUserService.queryByCondition(queryCondition,orderStr, pageVo.getStartIndex(), pageVo.getPageSize());  //按条件查询全部,带排序
	        conf(beans);
	        //翻译状态码
        	if(beans!=null){
	        	for(RmUserVo bean:beans){
				//如果状态码字段有其他用途，请用扩展字段attribute1-attribute5代替
	        		if(ISystemConstant.DICTIONARY_RM_YES_NOT_1.equals(bean.getLogin_status())){
	        			bean.setLogin_status("已登录");
	        		}else{
	        			bean.setLogin_status("未登录");
	        		}
	        		if(bean.getAuthen_type()==null){
	        			bean.setAuthen_type("");
	        		}
	        	}
        	}
        	
        	dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
	        dataMap.put(ISystemConstant.PAGE_DRAW, request.getParameter(ISystemConstant.PAGE_DRAW));
	        //"recordsTotal"
        	dataMap.put(ISystemConstant.RECORDS_TOTAL,totalNum);
	        dataMap.put(ISystemConstant.RECORDS_FILTERED, totalNum);
        	dataMap.put(ISystemConstant.DATA, beans);
        	return dataMap;
          }catch(Exception e){
        	  e.printStackTrace();
        	  RmProjectHelper.logInf(StringHelper.exceptionToString(e));
        	  dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
        	  dataMap.put(ISystemConstant.AJAX_MESSAGE, "查询失败!");
        	  return dataMap;
          }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);	        
          }
    }
    
    public void conf(List<RmUserVo> vo){
    	String parent_party_name="";
    	StringBuilder orgFullPath = new StringBuilder();
		try {
			for(RmUserVo vos : vo ){
				orgFullPath = new StringBuilder();
				vos.setCustom5(null);
			if(vos.getParent_party_id() != null && vos.getParent_party_id().toString().length() > 0) {
				RmCommonVo thisParent = new RmCommonVo();
				thisParent.put("parent_party_code", vos.getParent_party_code().toString());
				List<RmCommonVo> lThisParent = new ArrayList<RmCommonVo>();
				lThisParent.add(thisParent);
				List<RmCommonVo> lParent = RmOrgService.getInstance().listAncestor(vos.getParent_party_id().toString(), IOrgauthConstants.PartyView.DEFAULT.id(), lThisParent);
				//lParent.remove(0);
				for(RmCommonVo vo1 : lParent) {
					if(orgFullPath.length() > 0) {
						vos.setCustom4(orgFullPath.toString());
						orgFullPath.append("->");
					}
					orgFullPath.append(vo1.getString("child_party_name"));
					vos.setCustom3(vo1.getString("child_party_name"));
				}
				
				vos.setCustom5(orgFullPath.toString());
			}
			}
		}catch(Exception e) {
			e.printStackTrace();
			orgFullPath.append(parent_party_name.toString());
		}
    }
    /**
     * 从页面表单获取信息注入vo，并更新单条记录
     * @param request http请求对象
     * @param vo 值对象
     * @return 返回Ajax应答实体对象
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST, 
			consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> update(HttpServletRequest request, @Valid RmUserVo vo) {
          boolean bLock = false;
          try{
        	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        Map<String, Object> result = new HashMap<String, Object>();
	        try{
	            RmPopulateHelper.populate(vo, request);  //从request中注值进去vo
	            String uuid=vo.getAttribute2()==null?"":vo.getAttribute2();
	       	 	String md5Password=getPubParamService().signRmUserPwd(uuid, vo.getPassword());
	            vo.setPassword(md5Password);//将用户的密码加密处理
	            RmVoHelper.markModifyStamp(request,vo);  //打修改时间,IP戳
	            int count = 0;
	        	if(IOrgauthConstants.Config.isUserRelationParty.value()) {
	        		String pratyViewId = request.getParameter("view_id");
	        		String partyTypeId = request.getParameter("party_type_id");
	        		String isInherit = request.getParameter("isInherit");
	        		String[] parentPartyIds = RmStringHelper.parseToArrayIgnoreEmpty(request.getParameter("organization_id"), ",");
	        		String[] parentPartyNames = RmStringHelper.parseToArrayIgnoreEmpty(request.getParameter("organization_name"), ",");
	        		String[] oldParentPartyIds = RmStringHelper.parseToArrayIgnoreEmpty(request.getParameter("oldParentPartyIds"), ",");
	        		String oldName = request.getParameter("oldName");
	        		vo.setAttribute1(request.getParameter("organization_name"));
	        		count = RmCustomOrgService.getInstance().updateParty(vo, pratyViewId,oldName, partyTypeId, parentPartyIds,oldParentPartyIds ,isInherit);  //更新单条记录
	        		//vo.setOrganization_id("");2015/4/28
	        	} else {
	        		count = iRmUserService.update(vo);  //更新单条记录
	        	}
	        	
	            request.setAttribute(EXECUTE_ROW_COUNT, count);  //sql影响的行数放入request属性
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		        result.put(ISystemConstant.AJAX_MESSAGE, "更新用户成功!" );
	        }catch(Exception e){
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
		        result.put(ISystemConstant.AJAX_MESSAGE, "更新用户失败!");	        	
	        }
	        return result;
          }finally{
    		//最后解锁
    		RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
          }
    }
    /**
     * 删除单条记录
     * @param request http请求对象
     * @return 返回Ajax应答实体对象
     */
    @RequestMapping(value = "/delete", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> delete(HttpServletRequest request) {
          boolean bLock = false;
          try{
        	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
	        Map<String, Object> result = new HashMap<String, Object>();
	        try{
	        	iRmUserService.delete(request.getParameter(REQUEST_ID));
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		        result.put(ISystemConstant.AJAX_MESSAGE, "删除用户成功!" );
	        }catch(Exception e){
	        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
		        result.put(ISystemConstant.AJAX_MESSAGE, "删除用户失败!");	        	
	        }
	        return result;
          }finally{
    		//最后解锁
    		RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
          }
    }
    /**
     * 功能: 从request中获得查询条件
     *
     * @param request
     * @return
     */
    protected String getQueryCondition(HttpServletRequest request) {
        String queryCondition = null;
        if(request.getAttribute(REQUEST_QUERY_CONDITION) != null) {  //如果request.getAttribute中有，就不取request.getParameter
            queryCondition = request.getAttribute(REQUEST_QUERY_CONDITION).toString();
        } else {
			List<String> lQuery = new ArrayList<String>();
			
			if(IOrgauthConstants.Config.isUserRelationParty.value()) {
				org.quickbundle.project.login.RmUserVo userVo = (org.quickbundle.project.login.RmUserVo)RmProjectHelper.getRmUserVo(request);
				if(userVo !=null && !IOrgauthConstants.UserAdminType.ADMIN.value().equals(userVo.getAdmin_type()) && userVo.getParty_id_org()!=null){
					RmCommonVo cVo = RmProjectHelper.getCommonServiceInstance().doQuery("select distinct(PR.CHILD_PARTY_CODE) from RM_PARTY_RELATION PR where PR.CHILD_PARTY_ID=" + userVo.getParty_id_org()+" and PR.PARTY_VIEW_ID="+IOrgauthConstants.PartyView.DEFAULT.id()).get(0);
					lQuery.add("exists(select * from RM_USER U2 join RM_PARTY_RELATION PR on U2.ID=PR.CHILD_PARTY_ID where U2.USABLE_STATUS='1' and U2.ID=RM_USER.ID and PR.CHILD_PARTY_CODE like '" + cVo.getString("child_party_code") + "%')");
				}
			}
			if(request.getParameter("parent_party_id") != null && request.getParameter("parent_party_id").length() > 0) {
				lQuery.add("RM_PARTY_RELATION.CHILD_PARTY_CODE LIKE " +
						"" +
						"(select " +
						RmSqlHelper.getFunction(RmSqlHelper.Function.CONCAT, RmConfig.getSingleton().getDatabaseProductName(), 
								"PR9.CHILD_PARTY_CODE", "'%'") +
						" FROM RM_PARTY_RELATION PR9 WHERE PR9.CHILD_PARTY_ID=" + request.getParameter("parent_party_id") + 
						")");
			}
			
			if (!StringHelper.isEmpty(request.getParameter("userName"))) {
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".name", request.getParameter("userName"), RmSqlHelper.TYPE_CHAR_LIKE));
			} else {
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".name", request.getParameter("name"), RmSqlHelper.TYPE_CHAR_LIKE));
			}
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".lock_status", request.getParameter("lock_status"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".login_id", request.getParameter("login_id"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".password", request.getParameter("password"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".authen_type", request.getParameter("authen_type"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".organization_id", request.getParameter("organization_id"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".employee_id", request.getParameter("employee_id"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".email", request.getParameter("email"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".admin_type", request.getParameter("admin_type"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".description", request.getParameter("description"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".agent_status", request.getParameter("agent_status"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".login_status", request.getParameter("login_status"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
			
    		lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".last_login_date", request.getParameter("last_login_date_from"), RmSqlHelper.TYPE_DATE_GREATER_EQUAL));
    		lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".last_login_date", request.getParameter("last_login_date_to"), RmSqlHelper.TYPE_DATE_LESS_EQUAL));	
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".last_login_ip", request.getParameter("last_login_ip"), RmSqlHelper.TYPE_CHAR_LIKE));
			
    		lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".login_sum", request.getParameter("login_sum_from"), RmSqlHelper.TYPE_NUMBER_GREATER_EQUAL));
    		lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".login_sum", request.getParameter("login_sum_to"), RmSqlHelper.TYPE_NUMBER_LESS_EQUAL));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".last_custom_css", request.getParameter("last_custom_css"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".is_affix", request.getParameter("is_affix"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".function_permission", request.getParameter("function_permission"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".data_permission", request.getParameter("data_permission"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".custom1", request.getParameter("custom1"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".custom2", request.getParameter("custom2"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".custom3", request.getParameter("custom3"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".custom4", request.getParameter("custom4"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".custom5", request.getParameter("custom5"), RmSqlHelper.TYPE_CHAR_LIKE));
			
			lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".custom_xml", request.getParameter("custom_xml"), RmSqlHelper.TYPE_CHAR_LIKE));

			queryCondition = RmSqlHelper.appendQueryStr(lQuery.toArray(new String[0]));
        }
        return queryCondition;
    }
    protected int getCount(String queryCondition) {
    	int count = RmSqlCountCache.getCount(TABLE_NAME, queryCondition);
    	if(count < 0) {
    		count = iRmUserService.getRecordCount(queryCondition);
    		RmSqlCountCache.putCount(TABLE_NAME, queryCondition, count);
    	}
    	return count;
    }
  public PubParamService getPubParamService() {
    	
        return (PubParamService) RmBeanFactory.getBean(PubParamService.class.getName());  //得到Service对象,受事务控制
        
    }
  /**
   * 批量生成安全密码
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  //重置密码
  @RequestMapping(value = "/reSetPassword")
  @ResponseBody
  public Map<String,Object> reSetPassword( HttpServletRequest request, HttpServletResponse response) throws Exception {
	  Map<String, Object> result = new HashMap<String, Object>();
	  String idss =request.getParameter("ids");
	  String[] ids = RmJspHelper.getArrayFromRequest(request, REQUEST_IDS);  //从request获取多条记录id
      StringBuilder info = new StringBuilder();
      int count = 0;  //定义成功删除的记录数
      String alertStr="";
      if (ids != null && ids.length != 0) {
      	for(String id : ids) {
      		try {
      			count += iRmUserService.updatePassword(id); //生成安全密码
				} catch (Exception e) {
					RmUserVo vo = iRmUserService.find(id);
					info.append("<div>");
					info.append(vo.getLogin_id());
					info.append(", ");
					info.append(vo.getName());
					info.append(", ");
					info.append(vo.getEmail());
					info.append(", ");
					info.append(e.toString());
					info.append("</div>");
				}
      	}
      	request.setAttribute(EXECUTE_ROW_COUNT, count);  //sql影响的行数放入request属性
          if(info.length() > 0) {
          	request.getSession().setAttribute("info", info.toString());
          }
          alertStr = "成功更新" + count + "条";
          result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
	      result.put(ISystemConstant.AJAX_MESSAGE, "更改用户密码成功!" );
          if((ids.length - count) > 0) {
          	alertStr += ", 失败" + (ids.length - count) + "条";
          	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
	        result.put(ISystemConstant.AJAX_MESSAGE, "更改用户密码失败!");	
          }
      }else{
      	request.setAttribute(EXECUTE_ROW_COUNT, 0);  //sql影响的行数放入request属性
      }
      //RmJspHelper.goUrlWithAlert(request, response, alertStr, mapping.findForward(FORWARD_TO_QUERY_ALL).getPath());
      return result;
  }
	  /**
	     * 从页面表单获取信息注入vo，并更新单条记录
	     * @param request http请求对象
	     * @param vo 值对象
	     * @return 返回Ajax应答实体对象
	     */
  		//更新用户权限
	    @RequestMapping(value = "/insertPartyRole")
	    @ResponseBody
	    public Map<String,Object> insertPartyRole(HttpServletRequest request) {
	          boolean bLock = false;
	          try{
	        	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
		        Map<String, Object> result = new HashMap<String, Object>();
		        try{
		        	String id = request.getParameter("id");
		    		String[] role_ids = request.getParameterValues("role_name");
		    		if (RmStringHelper.checkNotEmpty(id)) {
		    			iRmRoleService.insertRm_party_roles(id, role_ids);
		    		}
		        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
			        result.put(ISystemConstant.AJAX_MESSAGE, "权限更新成功!" );
		        }catch(Exception e){
		        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
			        result.put(ISystemConstant.AJAX_MESSAGE, "权限更新失败!");	        	
		        }
		        return result;
	          }finally{
	    		//最后解锁
	    		RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
	          }
	    }
	    /**
	     * 从页面表单获取信息注入vo，并更新单条记录
	     * @param request http请求对象
	     * @param vo 值对象
	     * @return 返回Ajax应答实体对象
	     */
	    @RequestMapping(value = "/insert", method = RequestMethod.POST, 
				consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
	    @ResponseBody
	    public Map<String,Object> insert(HttpServletRequest request, @Valid RmUserVo vo) {
	          boolean bLock = false;
	          try{
	        	bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));        	
		        Map<String, Object> result = new HashMap<String, Object>();
		        try{
		             RmPopulateHelper.populate(vo, request);  //从request中注值进去vo
		             String uuid=vo.getAttribute2()==null?"":vo.getAttribute2();
		        	 	String md5Password=getPubParamService().signRmUserPwd(uuid, vo.getPassword());
		             vo.setPassword(md5Password);//将用户的密码加密处理
		             RmVoHelper.markCreateStamp(request,vo);  //打创建时间,IP戳
		             Timestamp ts = new Timestamp(System.currentTimeMillis());  
		             vo.setCreate_time(ts);
		             String id = null;
		             if(IOrgauthConstants.Config.isUserRelationParty.value()) {
		             	String pratyViewId = request.getParameter("view_id");
		             	String partyTypeId = request.getParameter("party_type_id");
		             	String isInherit = request.getParameter("isInherit");
		             	String[] parentPartyIds =null;
		             	String organizationIds = request.getParameter("organization_id");
		             	if(!StringHelper.isEmpty(organizationIds)){
		             		parentPartyIds = organizationIds.trim().split(",");
		             	}
		             	String[] organizationNames = request.getParameter("organizationName").split(",");
		             	//vo.setOrganization_id("");
		             	id = RmCustomOrgService.getInstance().insertParty(vo, pratyViewId, partyTypeId, parentPartyIds,organizationNames,isInherit);  //插入单条记录
		             } else {
		             	id = iRmUserService.insert(vo);  //插入单条记录
		             }
		             request.setAttribute(IGlobalConstants.INSERT_FORM_ID, id);
		        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
			        result.put(ISystemConstant.AJAX_MESSAGE, "添加用户成功!" );
		        }catch(Exception e){
		        	result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
			        result.put(ISystemConstant.AJAX_MESSAGE, "添加	用户失败!");	        	
		        }
		        return result;
	          }finally{
	    		//最后解锁
	    		RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
	          }
	    }
	    
	   
}
